<template>
  <div class="app-container">
    <!-- 主导航栏 -->
    <el-container>
      <el-header height="auto" class="main-header">
        <div class="header-content">
          <div class="logo-section">
            <div
              class="logo"
              :style="{ backgroundImage: `url(${logoURL})` }"
            ></div>
            <h1>智寻失物云栈</h1>
          </div>

          <el-menu
            v-show="routeReady"
            mode="horizontal"
            router
            class="nav-menu"
            :ellipsis="false"
            :default-active="activeMenu"
          >
            <el-menu-item index="/">
              <el-icon><House /></el-icon>首页
            </el-menu-item>
            <el-menu-item index="/lost">
              <el-icon><Search /></el-icon>寻物启事
            </el-menu-item>
            <el-menu-item index="/found">
              <el-icon><Collection /></el-icon>失物招领
            </el-menu-item>
            <el-menu-item index="/publish">
              <el-icon><Edit /></el-icon>发布信息
            </el-menu-item>
            <el-menu-item index="/guide">
              <el-icon><Guide /></el-icon>使用指南
            </el-menu-item>
          </el-menu>

          <!-- 修改用户区域部分 -->
          <div class="user-section">
            <!-- 始终显示用户头像 -->
            <el-dropdown @command="handleCommand">
              <div class="avatar-container">
                <el-avatar
                  :size="32"
                  :src="isLoggedIn ? userInfo.avatar : defaultAvatar"
                />
                <span
                  class="username"
                  style="
                    -webkit-user-select: none; /* Safari */
                    -moz-user-select: none; /* Firefox */
                    -ms-user-select: none; /* Internet Explorer/Edge */
                    user-select: none;
                  "
                  >{{ isLoggedIn ? userInfo.name : "未登录" }}</span
                >
              </div>
              <template #dropdown>
                <el-dropdown-menu>
                  <template v-if="isLoggedIn">
                    <el-dropdown-item command="userCenter">
                      <el-icon><User /></el-icon>个人中心
                    </el-dropdown-item>
                    <el-dropdown-item command="logout">
                      <el-icon><SwitchButton /></el-icon>退出登录
                    </el-dropdown-item>
                  </template>
                  <template v-else>
                    <el-dropdown-item command="login">
                      <el-icon><Key /></el-icon>登录
                    </el-dropdown-item>
                    <el-dropdown-item command="register">
                      <el-icon><UserFilled /></el-icon>注册
                    </el-dropdown-item>
                  </template>
                </el-dropdown-menu>
              </template>
            </el-dropdown>
          </div>
        </div>
      </el-header>

      <!-- 主要内容区 -->
      <el-container class="main-container">
        <!-- 左侧边栏 -->
        <el-aside width="250px" class="left-sidebar">
          <div class="sidebar-slogan">
            <span>拾光归处</span>
          </div>

          <!-- 添加拾物英雄榜到侧边栏 -->
          <el-card class="hero-card">
            <template #header>
              <div class="sidebar-header">
                <span>拾物英雄榜</span>
              </div>
            </template>
            <SidebarHeroList />
          </el-card>
        </el-aside>

        <!-- 主内容区 -->
        <el-main>
          <router-view></router-view>
        </el-main>

        <!-- 右侧边栏 -->
        <el-aside width="250px" class="right-sidebar">
          <el-card class="contact-card">
            <template #header>
              <div class="sidebar-header">
                <span>联系我们</span>
              </div>
            </template>
            <div class="contact-info">
              <p>
                <el-icon><Phone /></el-icon> 服务热线：123-4567-8900
              </p>
              <p>
                <el-icon><Message /></el-icon> 服务邮箱：help@school.edu.cn
              </p>
              <p>
                <el-icon><Timer /></el-icon> 工作时间：周一至周五 9:00-17:00
              </p>
            </div>
          </el-card>

          <el-card class="qr-code-card">
            <template #header>
              <div class="sidebar-header">
                <span>关注我们</span>
              </div>
            </template>
            <div class="qr-code">
              <el-icon :size="160"><QrCode /></el-icon>
              <p>扫码关注公众号</p>
            </div>
          </el-card>
        </el-aside>
      </el-container>

      <!-- 页脚 -->
      <el-footer height="auto" class="main-footer">
        <div class="footer-content">
          <div class="footer-section">
            <h3>关于我们</h3>
            <p>校园失物招领平台致力于帮助师生快速找回失物，传递校园温暖。</p>
          </div>
          <div class="footer-section">
            <h3>快速链接</h3>
            <ul>
              <li><router-link to="/guide">使用指南</router-link></li>
              <li><router-link to="/about">关于我们</router-link></li>
              <li><router-link to="/contact">联系我们</router-link></li>
            </ul>
          </div>
          <div class="footer-section">
            <h3>联系方式</h3>
            <p>
              <el-icon><Location /></el-icon> 地址：校园大道123号
            </p>
            <p>
              <el-icon><Phone /></el-icon> 电话：123-4567-8900
            </p>
            <p>
              <el-icon><Message /></el-icon> 邮箱：help@school.edu.cn
            </p>
          </div>
        </div>
        <div class="footer-bottom">
          <p>© 2024 校园失物招领平台 版权所有</p>
        </div>
      </el-footer>
    </el-container>

    <!-- 登录对话框 -->
    <el-dialog
      v-model="loginDialogVisible"
      title="用户登录"
      width="400px"
      destroy-on-close
    >
      <login-form
        :default-username="loginFormUsername"
        @success="handleLoginSuccess"
        @register="showRegisterDialog"
      />
    </el-dialog>

    <!-- 注册对话框 -->
    <el-dialog
      v-model="registerDialogVisible"
      title="用户注册"
      width="500px"
      destroy-on-close
    >
      <register-form
        @success="handleRegisterSuccess"
        @login="showLoginDialog"
        @login-success="handleLoginSuccess"
      />
    </el-dialog>
  </div>
</template>

<script>
import { ref, onMounted, computed, onUnmounted } from "vue";
import {
  House,
  Search,
  Collection,
  Edit,
  Guide,
  Message,
  Location,
  Phone,
  Timer,
  QrCode,
  User,
  SwitchButton,
  Key,
  UserFilled,
} from "@element-plus/icons-vue";
import SidebarHeroList from "@/components/SidebarHeroList.vue";
import { ElMessage } from "element-plus";
import { useRouter, useRoute } from "vue-router";
import LoginForm from "@/components/LoginForm.vue";
import RegisterForm from "@/components/RegisterForm.vue";

export default {
  name: "App",
  components: {
    House,
    Search,
    Collection,
    Edit,
    Guide,
    Message,
    Location,
    Phone,
    Timer,
    QrCode,
    User,
    SwitchButton,
    Key,
    UserFilled,
    SidebarHeroList,
    LoginForm,
    RegisterForm,
  },
  setup() {
    const logoURL = ref(
      "https://haowallpaper.com/link/common/file/previewFileImg/16463882335866240"
    );
    const route = useRoute();
    const router = useRouter();
    const routeReady = ref(false);

    // 使用组合计算属性确保在路由准备好前不执行
    const activeMenu = computed(() => {
      if (!routeReady.value) return ""; // 返回空字符串，不高亮任何菜单项
      return route.path;
    });

    // 确保路由已准备好
    onMounted(async () => {
      await router.isReady();
      routeReady.value = true;
      router.afterEach(() => {
        window.scrollTo(0, 0);
      });

      // 添加头像更新事件监听
      window.addEventListener("userAvatarUpdated", updateGlobalAvatar);
    });

    // 组件卸载时移除事件监听器
    onUnmounted(() => {
      window.removeEventListener("userAvatarUpdated", updateGlobalAvatar);
    });

    // 用户登录状态管理
    const isLoggedIn = ref(false);
    const userInfo = ref({
      id: "",
      name: "",
      avatar: "",
    });

    // 登录对话框状态
    const loginDialogVisible = ref(false);
    const registerDialogVisible = ref(false);
    const loginFormUsername = ref("");

    // 默认头像
    const defaultAvatar =
      "https://cube.elemecdn.com/3/7c/3ea6beec64369c2642b92c6726f1epng.png";

    // 检查登录状态
    const checkLoginStatus = () => {
      const token = localStorage.getItem("token");
      if (token) {
        isLoggedIn.value = true;
        // 从本地存储加载用户信息
        const savedUserInfo = localStorage.getItem("userInfo");
        if (savedUserInfo) {
          userInfo.value = JSON.parse(savedUserInfo);
        } else {
          // 如果没有用户信息但有token，可以调用API获取
          // fetchUserInfo();
        }
      } else {
        isLoggedIn.value = false;
        userInfo.value = {
          id: "",
          name: "",
          avatar: "",
        };
      }
    };

    // 处理下拉菜单命令
    const handleCommand = (command) => {
      if (command === "userCenter") {
        router.push("/user");
      } else if (command === "logout") {
        logout();
      } else if (command === "login") {
        showLoginDialog();
      } else if (command === "register") {
        showRegisterDialog();
      }
    };

    // 退出登录
    const logout = () => {
      // 可以先调用后端登出API
      // 然后清除本地存储
      localStorage.removeItem("token");
      localStorage.removeItem("userInfo");
      isLoggedIn.value = false;
      ElMessage.success("退出登录成功");

      // 如果当前在需要登录的页面，重定向到首页
      const currentRoute = router.currentRoute.value;
      if (currentRoute.meta.requiresAuth) {
        router.push("/");
      }
    };

    // 显示登录对话框
    const showLoginDialog = () => {
      loginDialogVisible.value = true;
    };

    // 显示注册对话框
    const showRegisterDialog = () => {
      registerDialogVisible.value = true;
    };

    // 处理登录成功
    const handleLoginSuccess = (data) => {
      isLoggedIn.value = true;
      userInfo.value = {
        id: data.id,
        name: data.name || data.username, // 兼容注册后没有name的情况
        avatar: data.avatar || defaultAvatar, // 兼容注册后没有头像的情况
      };

      // 存储token和用户信息
      localStorage.setItem("token", data.token);
      localStorage.setItem(
        "userInfo",
        JSON.stringify({
          id: data.id,
          name: data.name || data.username,
          avatar: data.avatar || defaultAvatar,
        })
      );

      // 关闭所有对话框
      loginDialogVisible.value = false;
      registerDialogVisible.value = false;

      // 显示成功消息
      ElMessage.success("登录成功");

      // 如果有重定向URL，则跳转
      const redirectUrl = localStorage.getItem("redirectUrl");
      if (redirectUrl) {
        router.push(redirectUrl);
        localStorage.removeItem("redirectUrl");
      }
    };

    // 处理注册成功
    const handleRegisterSuccess = (data) => {
      registerDialogVisible.value = false;
      loginDialogVisible.value = true;
      // 如果传入了用户名，则设置到登录表单预填
      if (data && data.username) {
        loginFormUsername.value = data.username;
      }
    };

    // 添加用于更新全局头像的事件监听器
    const updateGlobalAvatar = (event) => {
      if (event.detail && event.detail.avatar) {
        console.log("App收到头像更新事件:", event.detail.avatar);

        // 获取最新用户信息
        const userInfoStr = localStorage.getItem("userInfo");
        if (userInfoStr) {
          try {
            const storedUserInfo = JSON.parse(userInfoStr);

            // 更新全局头像状态 - 根据您的App结构调整
            if (userInfo.value) {
              userInfo.value.avatar = storedUserInfo.avatar;
              console.log("App全局头像已更新");
            }

            // 或者重新检查登录状态获取最新信息
            checkLoginStatus();
          } catch (e) {
            console.error("解析用户信息失败", e);
          }
        }
      }
    };

    onMounted(() => {
      checkLoginStatus();
    });

    return {
      logoURL,
      activeMenu,
      isLoggedIn,
      userInfo,
      defaultAvatar,
      loginDialogVisible,
      registerDialogVisible,
      loginFormUsername,
      handleCommand,
      showLoginDialog,
      showRegisterDialog,
      handleLoginSuccess,
      handleRegisterSuccess,
      routeReady,
    };
  },
};
</script>

<style>
/* 在样式的开头添加背景图片 */
.app-container {
  background-image: url("http://localhost:65535/upload/images/beijing.png");
  background-size: cover;
  background-attachment: fixed;
  background-position: center;
  min-height: 100vh;
}

/* 全局背景设置 */
html,
body {
  margin: 0;
  padding: 0;
  background-image: url("http://localhost:65535/upload/images/beijing.png");
  background-size: cover;
  background-attachment: fixed;
  background-position: center;
  min-height: 100vh;
}

/* 在样式的开头添加背景图片 */
.app-container {
  position: relative;
  min-height: 100vh;
}

.app-container::before {
  content: "";
  position: absolute;
  top: 0;
  left: 0;
  width: 100%;
  height: 100%;
  background-image: url("http://localhost:65535/upload/images/beijing.png");
  background-size: cover;
  background-attachment: fixed;
  background-position: center;
  opacity: 0.15; /* 调整透明度 */
  z-index: -1;
}

/* 确保内容区域有适当的背景 */
.main-container {
  background-color: transparent; /* 改为透明背景 */
  border-radius: 8px;
  box-shadow: none; /* 移除阴影 */
  margin: 15px;
}

/* 修改全局背景色 */
body {
  margin: 0;
  padding: 0;
  background-color: #d0dae7; /* 更深的基础色 */
}

.app-container {
  min-height: 100vh;
  display: flex;
  flex-direction: column;
  background-color: #f5f5dc; /* 浅蓝色护眼色 */
}

/* 调整卡片样式以配合深色背景 */
.el-card {
  border: none;
  box-shadow: 0 2px 12px rgba(0, 0, 0, 0.1);
  transition: box-shadow 0.3s ease;
}

.el-card:hover {
  box-shadow: 0 4px 16px rgba(0, 0, 0, 0.15);
}

/* 主导航栏样式 */
.main-header {
  box-shadow: var(--box-shadow);
  padding: 0;
  background-color: transparent; /* 移除背景色 */
}

.header-content {
  max-width: 1200px;
  margin: 0 auto;
  padding: 10px 20px;
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.logo-section {
  display: flex;
  align-items: center;
  gap: 15px;
}

.logo {
  height: 40px;
  width: 40px;
  background-size: contain;
  background-position: center;
  background-repeat: no-repeat;
  /* 添加圆角 */
  border-radius: 50%;
}

.nav-menu {
  background-color: transparent !important; /* 移除背景色 */
  --el-menu-hover-bg-color: rgba(0, 0, 0, 0.05) !important; /* 淡化悬停效果 */
  --el-menu-text-color: #333333 !important; /* 改为深色文字 */
  --el-menu-active-color: #409eff !important; /* 使用默认的蓝色作为激活颜色 */
  border-bottom: 1px solid #e6e6e6 !important; /* 添加细边框分隔 */
  border: none;
  padding: 0 10px;
}

.nav-menu .el-menu-item {
  color: #333333 !important; /* 改为深色文字 */
  font-weight: 500;
  padding: 0 20px;
  height: 50px;
  line-height: 50px;
}

.nav-menu .el-menu-item:hover {
  background-color: rgba(0, 0, 0, 0.05) !important; /* 淡化悬停效果 */
}

.nav-menu .el-menu-item.is-active {
  color: #409eff !important; /* 使用默认的蓝色作为激活颜色 */
  font-weight: bold;
  background-color: transparent !important; /* 移除激活背景 */
  border-bottom: 2px solid #409eff; /* 保留底边线标识激活项 */
}

.logo-section h1 {
  color: #333; /* 改为深色文字 */
  margin: 0;
  font-size: 20px;
}

.user-section {
  display: flex;
  align-items: center;
}

.avatar-container {
  display: flex;
  align-items: center;
  gap: 8px;
}

.username {
  font-weight: bold;
  font-size: 14px;
  color: #333; /* 改为深色文字 */
}

/* 主要内容区样式 */
.el-main {
  max-width: 1200px;
  margin: 0 auto;
  padding: 20px;
  min-height: 600px;
}

/* 页脚样式 */
.main-footer {
  background-color: var(--text-primary);
  color: var(--card-bg);
  padding: 40px 0 0 0;
}

.footer-content {
  max-width: 1200px;
  margin: 0 auto;
  padding: 0 20px;
  display: grid;
  grid-template-columns: repeat(3, 1fr);
  gap: 40px;
}

.footer-section h3 {
  margin-bottom: 20px;
  font-size: 18px;
  color: #ffffff;
}

.footer-section ul {
  list-style: none;
  padding: 0;
}

.footer-section ul li {
  margin-bottom: 10px;
}

.footer-section a {
  color: #ffffff;
  text-decoration: none;
}

.footer-section p {
  margin-bottom: 10px;
  display: flex;
  align-items: center;
  gap: 8px;
}

.footer-bottom {
  margin-top: 40px;
  padding: 20px;
  text-align: center;
  border-top: 1px solid rgba(255, 255, 255, 0.1);
}

/* 响应式设计 */
@media (max-width: 768px) {
  .footer-content {
    grid-template-columns: 1fr;
  }

  .header-content {
    flex-direction: column;
    gap: 20px;
  }

  .top-bar {
    flex-direction: column;
    gap: 10px;
  }
}

.el-button--primary {
  background-color: var(--primary-color);
  border-color: var(--primary-color);
}

.el-button--success {
  background-color: var(--success-color);
  border-color: var(--success-color);
}

.main-container {
  max-width: 1600px;
  margin: 0 auto;
  padding: 20px;
  display: flex;
  gap: 20px;
}

.left-sidebar,
.right-sidebar {
  position: sticky;
  top: 20px;
  height: fit-content;
}

.quick-actions .action-btn {
  width: 100%;
  margin-bottom: 10px;
}

.quick-links {
  display: flex;
  flex-direction: column;
  gap: 12px;
}

.link-item {
  display: flex;
  align-items: center;
  gap: 8px;
  padding: 8px;
  cursor: pointer;
  border-radius: 4px;
  color: var(--text-secondary);
  transition: all 0.3s;
}

.link-item:hover {
  background-color: var(--bg-color);
  color: var(--primary-color);
}

.contact-info p {
  display: flex;
  align-items: center;
  gap: 8px;
  margin: 12px 0;
  color: var(--text-secondary);
}

.qr-code {
  text-align: center;
}

.qr-code img {
  width: 160px;
  height: 160px;
  margin-bottom: 10px;
}

.qr-code p {
  color: var(--text-secondary);
  font-size: 14px;
}

/* 响应式处理 */
@media (max-width: 1400px) {
  .left-sidebar,
  .right-sidebar {
    display: none;
  }
}

/* 修改 Element Plus 菜单默认样式 */
.el-menu {
  --el-menu-border-color: transparent !important;
}

.el-menu--horizontal {
  border-bottom: none !important;
}

.nav-menu {
  border: none !important;
  margin: 0 20px;
  flex: 1;
}

.sidebar-slogan {
  text-align: center;
  padding: 20px 0;
  margin-bottom: 20px;
  font-family: "STKaiti", "KaiTi", "楷体", serif;
  font-size: 28px;
  color: #1e90ff; /* 改为蓝色以增加可见性 */
  letter-spacing: 2px;
  font-weight: 500; /* 增加字体粗细 */
  border-bottom: 1px dashed #e0e0e0;
  line-height: 1.5;
  position: relative;
  text-shadow: 1px 1px 3px rgba(0, 0, 0, 0.1); /* 添加文字阴影增强可读性 */
}

.sidebar-slogan::after {
  content: "";
  position: absolute;
  bottom: -3px;
  left: 50%;
  width: 30px;
  height: 5px;
  background: linear-gradient(90deg, #1e90ff, #67c23a);
  transform: translateX(-50%);
  border-radius: 2px;
}

.hero-card {
  margin-top: 20px;
}

.sidebar-hero-list {
  /* 调整侧边栏中英雄榜的样式 */
  font-size: 0.85em;
  width: 100%;
  overflow: hidden;
}

/* 调整顶部英雄卡片 */
.sidebar-hero-list .top-heroes {
  flex-direction: column;
  align-items: center;
  gap: 10px;
  margin-bottom: 15px;
}

.sidebar-hero-list .top-hero-card {
  width: 85%;
  padding: 8px;
  height: auto !important;
  min-height: 120px;
}

/* 调整头像大小 */
.sidebar-hero-list .el-avatar {
  transform: scale(0.8);
}

/* 调整表格样式 */
.sidebar-hero-list .hero-table {
  font-size: 0.85em;
  width: 100% !important;
}

/* 调整表格列宽 */
.sidebar-hero-list .el-table__body,
.sidebar-hero-list .el-table__header {
  width: 100% !important;
}

/* 隐藏组件内部标题 */
.sidebar-hero-list .hero-header h3 {
  display: none;
}

/* 调整标签页样式 */
.sidebar-hero-list .header-tabs {
  margin-top: 5px;
  transform: scale(0.9);
  transform-origin: left center;
}

/* 调整更多链接 */
.sidebar-hero-list .more-link {
  font-size: 0.85em;
  margin-top: 5px;
}

/* 调整表格内部样式 */
.sidebar-hero-list .table-hero-stats {
  transform: scale(0.9);
}

/* 调整表格行高 */
.sidebar-hero-list .el-table__row {
  height: 50px;
}

/* 调整表格单元格内边距 */
.sidebar-hero-list .el-table .cell {
  padding-left: 5px;
  padding-right: 5px;
}

/* 调整排名数字大小 */
.sidebar-hero-list .rank-number {
  width: 20px;
  height: 20px;
  font-size: 12px;
}

/* 简化统计数据显示 */
.sidebar-hero-list .hero-stats {
  gap: 8px;
}

.sidebar-hero-list .stat-value {
  font-size: 16px;
}

.sidebar-hero-list .stat-label {
  font-size: 10px;
}

/* 调整表格中的头像列宽 */
.sidebar-hero-list .el-table__column:nth-child(2) {
  width: 40px !important;
}

/* 登录/注册对话框样式 */
.dialog-footer {
  display: flex;
  justify-content: flex-end;
  width: 100%;
  gap: 10px;
}

/* 标签页过渡效果 */
.el-tabs__content {
  overflow: hidden !important; /* 确保内容不会溢出 */
  transition: height 0.5s ease-in-out !important; /* 添加高度过渡 */
}

.el-tab-pane {
  transition: opacity 0.3s ease-in-out, transform 0.3s ease-in-out,
    max-height 0.5s ease-in-out !important;
  overflow: hidden !important; /* 确保内容不会溢出 */
}

/* 确保表单元素的平滑过渡 */
.el-form-item {
  transition: all 0.3s ease;
}

/* 确保表格的平滑过渡 */
.el-table {
  transition: all 0.3s ease;
}

/* 确保卡片内容的平滑过渡 */
.el-card__body {
  transition: all 0.5s ease-in-out !important; /* 增加过渡时间 */
}

/* 用户中心模块统一样式 - 更精确的控制 */
/* 设置固定宽度而不是最大宽度 */
.user-center-module {
  width: 800px !important; /* 使用固定宽度 */
}

/* 直接控制各个组件的内容宽度 */
.user-profile-form,
.avatar-upload,
.user-posts,
.user-notifications,
.security-settings {
  width: 800px !important;
}

/* 确保表单和表格宽度一致 */
.user-center-module .el-form,
.user-center-module .el-table,
.user-center-module .el-tabs,
.user-center-module .notification-list,
.user-center-module .avatar-container {
  width: 800px !important;
}

/* 确保表单项宽度一致 */
.user-center-module .el-form-item {
  width: 100%;
}

.user-center-module .el-form-item__content {
  width: 600px !important;
}

/* 确保输入框宽度一致 */
.user-center-module .el-input,
.user-center-module .el-select,
.user-center-module .el-textarea {
  width: 100% !important;
}

/* 确保表格列宽一致 */
.user-center-module .el-table__body,
.user-center-module .el-table__header {
  width: 800px !important;
}

.el-menu-item {
  -webkit-user-select: none; /* Safari */
  -moz-user-select: none; /* Firefox */
  -ms-user-select: none; /* Internet Explorer/Edge */
  user-select: none;
}
</style>
